import 'package:flutter/material.dart';
import 'package:play_android/com/zhihaoliang/base/BaseState.dart';
import 'package:play_android/com/zhihaoliang/const/AppEventBus.dart';
import 'package:play_android/com/zhihaoliang/const/AppStr.dart';
import 'package:play_android/com/zhihaoliang/const/Appkey.dart';
import 'package:play_android/com/zhihaoliang/http/HttpException.dart';
import 'package:play_android/com/zhihaoliang/play/login/event/LoginEvent.dart';
import 'package:play_android/com/zhihaoliang/play/presenter/LoginPresenter.dart';
import 'package:play_android/com/zhihaoliang/play/presenter/RegisterPresenter.dart';
import 'package:play_android/com/zhihaoliang/util/SpUtil.dart';
import 'package:play_android/com/zhihaoliang/util/ToastUtil.dart';

///  ***************************************************************************
///  登录页面
///  ***************************************************************************

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage>
    with BaseState
    implements LoginCallBack, RegisterCallBack {
  LoginPresenter _loginPresenter;

  RegisterPresenter _registerPresenter;

  TextEditingController _accountConer = TextEditingController(text: "");

  TextEditingController _pwdConer = TextEditingController(text: "");

  @override
  void initState() {
    super.initState();
    _loginPresenter = LoginPresenter(this);
    _registerPresenter = RegisterPresenter(this);
    initData();
  }

  void initData() {
    new SpUtil().getStrMapByList([AppKey.ACCOUNT, AppKey.PASSWORD]).then((map) {
      if (map == null) {
        return;
      }

      if (map[AppKey.ACCOUNT] == null) {
        return;
      }
      setState(() {
        _accountConer.text = map[AppKey.ACCOUNT];
        _pwdConer.text = map[AppKey.PASSWORD];
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    Row avatar = Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Icon(
          Icons.account_circle,
          color: Theme.of(context).accentColor,
          size: 80.0,
        ),
      ],
    );

    TextField accoutField = TextField(
      autofocus: true,
      decoration: InputDecoration(
        labelText: AppStr.ACCOUNT_COLON,
      ),
      controller: _accountConer,
    );

    TextField pwdField = TextField(
      decoration: InputDecoration(
        labelText: AppStr.PWD_COLON,
      ),
      obscureText: true,
      controller: _pwdConer,
    );

    Row loginAndRegister = Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        RaisedButton(
          child: Text(
            AppStr.LOGIN,
            style: TextStyle(color: Colors.white),
          ),
          color: Theme.of(context).accentColor,
          disabledColor: Colors.blue,
          onPressed: () {
            _login();
          },
        ),
        RaisedButton(
          child: Text(
            AppStr.REGISTER,
            style: TextStyle(color: Colors.white),
          ),
          color: Theme.of(context).accentColor,
          disabledColor: Colors.blue,
          onPressed: () {
            _register();
          },
        ),
      ],
    );

    return Scaffold(
      appBar: AppBar(
        title: Text(AppStr.LOGIN),
      ),
      body: Padding(
        padding: EdgeInsets.fromLTRB(40.0, 10.0, 40.0, 0.0),
        child: ListView(
          children: <Widget>[
            avatar,
            accoutField,
            pwdField,
            Padding(
              padding: EdgeInsets.fromLTRB(40.0, 10.0, 40.0, 0.0),
            ),
            loginAndRegister,
          ],
        ),
      ),
    );
  }

  ///登录操作
  void _login() {
    Map param = initParam();
    if (param == null) {
      return;
    }
    showLoadingDialog(context);
    _loginPresenter.load(param);
  }

  ///注册操作
  void _register() {
    Map param = initParam();
    if (param == null) {
      return;
    }

    param["repassword"] = param["password"];
    showLoadingDialog(context);
    _registerPresenter.load(param);
  }

  Map<String, String> initParam() {
    String account = _accountConer.text;
    if (account == null || account.length == 0) {
      ToastUtil.showWarn(context, AppStr.INPUT_ACCOUNT);
      return null;
    }

    String pwd = _pwdConer.text;
    if (pwd == null || pwd.length == 0) {
      ToastUtil.showWarn(context, AppStr.INPUT_PWD);
      return null;
    }

    return {"username": account, "password": pwd};
  }

  @override
  void onLoginComplete() {
    Map<String, String> param = initParam();

    Map keys = {
      AppKey.ACCOUNT: param["username"],
      AppKey.PASSWORD: param["password"]
    };

    SpUtil().saveByMap(keys).then((_) {
      dismissLoadingDialog(context);
      Navigator.of(context).pop();
      AppEventBus.eventBus.fire(LoginEvent(param["username"]));
    });
  }

  @override
  void onLoginError(HttpException httpException) {
    onTipError(httpException, context, AppStr.LOGIN_FAIl);
  }

  @override
  void onRegisterComplete() {
    Map param = initParam();
    SpUtil().saveByMap(param).then((_) {
      dismissLoadingDialog(context);
      ToastUtil.showWarn(context, AppStr.REGISTER_SUCESS);
    });
  }

  @override
  void onRegisterError(HttpException httpException) {
    onTipError(httpException, context, AppStr.REGISTER_FAIL);
  }
}
